iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
1
Mobile Development

新手試試用Flutter做Netflix UI系列 第 28

[Day28]初探Firebase Cloud Messaging for Flutter

  • 分享至 

  • xImage
  •  

大家好,今天要來嘗試使用firebase_messaging,今天使用的是Android手機

首先到Firebase Console註冊一個帳號,並建一個Project,註冊你的應用程式,並下載google-services.json,放到android/app

接著在/android/build.gradle 加上classpath 'com.google.gms:google-services:4.3.2'

//省略部分程式
buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.2'  //加的是這句
    }
}

在/android/app/build.gradle,中要加兩行
dependencies中加上
implementation 'com.google.firebase:firebase-messaging:20.3.0'
最下方加上
apply plugin: 'com.google.gms.google-services'

//省略部分程式
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-messaging:20.3.0'
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

新建一個Application.java

在app/src/main/kotlin/com/ignaciozhang/flutter_neflix_cover/Application.java
,內容如下

package com.ignaciozhang.flutter_neflix_cover; //這一行要改成自己的專案名稱

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    }
}

AndroidManifest.xml

接著在AndroidManifest.xml中,application裡面修改兩處
第一個是要加入這一段

            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

第二個是改名字

android:name=".Application"

改完的application應該會像這樣

<application
        android:name=".Application"
        android:label="flutter_neflix_cover"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

在main.dart中定義方法

這個是直接寫在import的下方,

import 'package:firebase_messaging/firebase_messaging.dart';

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
  if (message.containsKey('data')) {
    // Handle data message
    final dynamic data = message['data'];
  }

  if (message.containsKey('notification')) {
    // Handle notification message
    final dynamic notification = message['notification'];
  }

  // Or do other work.
}

initState中調用_firebaseMessaging.configure

進入的第一個StatefulWidget的initState裡面加上這段

 final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
 
  @override
  void initState() {
    super.initState();

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        // _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        // _navigateToItemDetail(message);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        // _navigateToItemDetail(message);
      },
    );
    
  }

測試

在firebase中進入cloud message,按照說明發送一個測試訊息
Day28
在Terminals中就看到,接到的訊息

I/flutter (28511): onMessage: {notification: {title: TEST, body: 測試通知文字}, data: {}}
I/flutter (28511): onMessage: {notification: {title: 測試2, body: 測試訊息2}, data: {}}

上一篇
[Day27]Flutter Netflix UI 使用json_serializable轉換Model
下一篇
[Day29]Flutter Netflix UI 底部導航欄上的通知數量
系列文
新手試試用Flutter做Netflix UI30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言